import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable_for_tencent_im/flutter_slidable.dart';
import 'package:tencent_im_base/tencent_im_base.dart';
import 'package:provider/provider.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_state.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_statelesswidget.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/separate_models/tui_group_profile_model.dart';

import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';

import 'package:tencent_cloud_chat_uikit/ui/widgets/avatar.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/radio_button.dart';
import 'package:tencent_cloud_chat_uikit/czm_custom_widget/czm_widget_bridge.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_base.dart';

class GroupProfileGroupManage extends TIMUIKitStatelessWidget {
  GroupProfileGroupManage({Key? key}) : super(key: key);

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    final TUITheme theme = value.theme;

    final model = Provider.of<TUIGroupProfileModel>(context);

    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => GroupProfileGroupManagePage(
              model: model,
            ),
          ),
        );
      },
      child: Container(
        padding: const EdgeInsets.only(top: 12, left: 16, bottom: 12),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(bottom: BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              TIM_t("群管理"),
              style: TextStyle(fontSize: 16, color: theme.darkTextColor),
            ),
            Icon(Icons.keyboard_arrow_right, color: theme.weakTextColor)
          ],
        ),
      ),
    );
  }
}

/// 管理员设置页面
class GroupProfileGroupManagePage extends StatefulWidget {
  final TUIGroupProfileModel model;

  const GroupProfileGroupManagePage({
    Key? key,
    required this.model,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _GroupProfileGroupManagePageState();
}

class _GroupProfileGroupManagePageState extends TIMUIKitState<GroupProfileGroupManagePage> {
  int? serverTime;

  @override
  void initState() {
    super.initState();
    getServerTime();
  }

  void getServerTime() async {
    final res = await TencentImSDKPlugin.v2TIMManager.getServerTime();
    setState(() {
      serverTime = res.data;
    });
  }

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider.value(value: widget.model),
          ChangeNotifierProvider.value(value: serviceLocator<TUIThemeViewModel>())
        ],
        builder: (context, w) {
          final memberList = Provider.of<TUIGroupProfileModel>(context).groupMemberList;
          final theme = Provider.of<TUIThemeViewModel>(context).theme;
          final isAllMuted = widget.model.groupInfo?.isAllMuted ?? false;
          return Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.white,
              title: Text(
                TIM_t("群管理"),
                style: const TextStyle(color: Colors.black, fontSize: 17),
              ),
              shadowColor: theme.weakDividerColor,
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(colors: [Colors.white, Colors.white]),
                ),
              ),
              iconTheme: const IconThemeData(
                color: Colors.white,
              ),
              leading: GestureDetector(
                onTap: () {
                  if (isAllMuted != widget.model.groupInfo?.isAllMuted) {
                    widget.model.setMuteAll(isAllMuted);
                  }
                  Navigator.pop(context);
                },
                child: CZMWidgetBuilderBridge.getInstance().appBarLeadingIcon(context),
              ),
            ),
            body: SlidableAutoCloseBehavior(
              child: ClipRect(
                child: Column(
                  children: [
                    if (widget.model.groupInfo?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER)
                      Container(
                        padding: const EdgeInsets.only(top: 12, left: 16, bottom: 12, right: 12),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(
                            bottom: BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor),
                          ),
                        ),
                        child: InkWell(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => GroupProfileSetManagerPage(
                                  model: widget.model,
                                ),
                              ),
                            );
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(TIM_t("设置管理员"), style: TextStyle(fontSize: 16, color: theme.darkTextColor)),
                              Icon(Icons.keyboard_arrow_right, color: theme.weakTextColor)
                            ],
                          ),
                        ),
                      ),
                    if (widget.model.groupInfo?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER)
                      Container(
                        padding: const EdgeInsets.only(top: 12, left: 16, bottom: 12, right: 12),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border(
                                bottom: BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor))),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              TIM_t("群消息撤回"),
                              style: TextStyle(fontSize: 16, color: theme.darkTextColor),
                            ),
                            CupertinoSwitch(
                              value: widget.model.groupCustomData?.revokeMsgOpt ?? false,
                              onChanged: (value) async {
                                widget.model.setRevokePermission(value);
                              },
                              activeColor: theme.primaryColor,
                            )
                          ],
                        ),
                      ),
                    Container(
                      padding: const EdgeInsets.only(top: 12, left: 16, bottom: 12, right: 12),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(
                              bottom: BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            TIM_t("全员禁言"),
                            style: TextStyle(fontSize: 16, color: theme.darkTextColor),
                          ),
                          CupertinoSwitch(
                            value: isAllMuted,
                            onChanged: (value) async {
                              widget.model.setMuteAll(value);
                            },
                            activeColor: theme.primaryColor,
                          )
                        ],
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                      color: theme.weakBackgroundColor,
                      alignment: Alignment.topLeft,
                      child: Text(
                        TIM_t("全员禁言开启后，只允许群主和管理员发言。"),
                        style: TextStyle(fontSize: 12, color: theme.weakTextColor),
                      ),
                    ),
                    if (!isAllMuted)
                      InkWell(
                        child: Container(
                            color: Colors.white,
                            padding: const EdgeInsets.only(left: 16),
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                vertical: 12,
                              ),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                      bottom:
                                          BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor))),
                              child: Row(
                                children: [
                                  Icon(
                                    Icons.add_circle_outline,
                                    color: theme.primaryColor,
                                    size: 20,
                                  ),
                                  const SizedBox(
                                    width: 12,
                                  ),
                                  Text(TIM_t("添加需要禁言的群成员"))
                                ],
                              ),
                            )),
                        onTap: () async {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => GroupProfileAddAdmin(
                                appbarTitle: TIM_t("设置禁言"),
                                memberList: memberList.where((element) {
                                  final isMute = (serverTime != null ? (element?.muteUntil ?? 0) > serverTime! : false);
                                  final isMember = element!.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_MEMBER;
                                  return !isMute && isMember;
                                }).toList(),
                                selectCompletedHandler: (context, selectedMember) async {
                                  if (selectedMember.isNotEmpty) {
                                    for (var member in selectedMember) {
                                      final userID = member!.userID;
                                      widget.model.muteGroupMember(userID, true, serverTime);
                                    }
                                  }
                                },
                              ),
                            ),
                          );
                        },
                      ),
                    if (!isAllMuted)
                      ...memberList
                          .where((element) => (serverTime != null ? (element?.muteUntil ?? 0) > serverTime! : false))
                          .map(
                            (e) => _buildListItem(
                              context,
                              e!,
                              ActionPane(
                                motion: const DrawerMotion(),
                                children: [
                                  SlidableAction(
                                    onPressed: (_) {
                                      widget.model.muteGroupMember(e.userID, false, serverTime);
                                    },
                                    flex: 1,
                                    backgroundColor: theme.cautionColor ?? CommonColor.cautionColor,
                                    autoClose: true,
                                    label: TIM_t("删除"),
                                  )
                                ],
                              ),
                            ),
                          )
                          .toList()
                  ],
                ),
              ),
            ),
          );
        });
  }
}

_getShowName(V2TimGroupMemberFullInfo? item) {
  final friendRemark = item?.friendRemark ?? "";
  final nameCard = item?.nameCard ?? "";
  final nickName = item?.nickName ?? "";
  return friendRemark.isNotEmpty
      ? friendRemark
      : nameCard.isNotEmpty
          ? nameCard
          : nickName;
}

Widget _buildListItem(BuildContext context, V2TimGroupMemberFullInfo memberInfo, ActionPane? endActionPane) {
  final theme = Provider.of<TUIThemeViewModel>(context).theme;
  return Container(
      color: Colors.white,
      child: ListView.builder(
          itemCount: 1,
          shrinkWrap: true,
          physics: const ClampingScrollPhysics(),
          itemBuilder: (context, index) {
            return Slidable(
                endActionPane: endActionPane,
                child: Column(children: [
                  ListTile(
                    tileColor: Colors.black,
                    leading: SizedBox(
                      width: 36,
                      height: 36,
                      child: Avatar(
                        faceUrl: memberInfo.faceUrl ?? "",
                        showName: _getShowName(memberInfo),
                        type: 2,
                      ),
                    ),
                    title: Row(
                      children: [
                        Text(_getShowName(memberInfo), style: const TextStyle(fontSize: 16)),
                      ],
                    ),
                    onTap: () {},
                  ),
                  Divider(thickness: 1, indent: 74, endIndent: 0, color: theme.weakDividerColor, height: 0)
                ]));
          }));
}

/// 选择管理员
class GroupProfileSetManagerPage extends StatefulWidget {
  final TUIGroupProfileModel model;

  const GroupProfileSetManagerPage({Key? key, required this.model}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _GroupProfileSetManagerPageState();
}

class _GroupProfileSetManagerPageState extends TIMUIKitState<GroupProfileSetManagerPage> {
  int? serverTime;

  List<V2TimGroupMemberFullInfo?> _getAdminMemberList(List<V2TimGroupMemberFullInfo?> memberList) {
    return memberList.where((member) => member?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_ADMIN).toList();
  }

  List<V2TimGroupMemberFullInfo?> _getOwnerList(List<V2TimGroupMemberFullInfo?> memberList) {
    return memberList.where((member) => member?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER).toList();
  }

  _removeAdmin(BuildContext context, V2TimGroupMemberFullInfo memberFullInfo) async {
    final res = await widget.model.setMemberToNormal(memberFullInfo.userID);
    if (res.code == 0) {
      onTIMCallback(TIMCallback(type: TIMCallbackType.INFO, infoRecommendText: TIM_t("成功取消管理员身份"), infoCode: 6661003));
    }
  }

  @override
  void initState() {
    super.initState();
    getServerTime();
  }

  void getServerTime() async {
    final res = await TencentImSDKPlugin.v2TIMManager.getServerTime();
    setState(() {
      serverTime = res.data;
    });
  }

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    final TUITheme theme = value.theme;

    return MultiProvider(
      providers: [ChangeNotifierProvider.value(value: widget.model)],
      builder: (context, w) {
        final model = Provider.of<TUIGroupProfileModel>(context);
        final memberList = model.groupMemberList;
        final adminList = _getAdminMemberList(memberList);
        final ownerList = _getOwnerList(memberList);
        final String option2 = adminList.length.toString();
        return Scaffold(
          appBar: AppBar(
            title: Text(
              TIM_t("设置管理员"),
              style: const TextStyle(color: Colors.white, fontSize: 17),
            ),
            shadowColor: theme.weakDividerColor,
            flexibleSpace: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(colors: [
                  theme.lightPrimaryColor ?? CommonColor.lightPrimaryColor,
                  theme.primaryColor ?? CommonColor.primaryColor
                ]),
              ),
            ),
            iconTheme: const IconThemeData(
              color: Colors.white,
            ),
          ),
          body: SlidableAutoCloseBehavior(
            child: SingleChildScrollView(
              child: ClipRect(
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.topLeft,
                      color: theme.weakDividerColor,
                      padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16),
                      child: Text(
                        TIM_t("群主"),
                        style: TextStyle(fontSize: 14, color: theme.weakTextColor),
                      ),
                    ),
                    ...ownerList
                        .map(
                          (e) => _buildListItem(context, e!, null),
                        )
                        .toList(),
                    Container(
                      alignment: Alignment.topLeft,
                      color: theme.weakDividerColor,
                      padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16),
                      child: Text(
                        TIM_t_para("管理员 ({{option2}})", "管理员 ($option2)")(option2: option2),
                        style: TextStyle(fontSize: 14, color: theme.weakTextColor),
                      ),
                    ),
                    InkWell(
                      child: Container(
                          color: Colors.white,
                          padding: const EdgeInsets.only(left: 16),
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              vertical: 12,
                            ),
                            decoration: BoxDecoration(
                                color: Colors.white,
                                border: Border(
                                    bottom: BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor))),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.add_circle_outline,
                                  color: theme.primaryColor,
                                  size: 20,
                                ),
                                const SizedBox(
                                  width: 12,
                                ),
                                Text(TIM_t("添加管理员"))
                              ],
                            ),
                          )),
                      onTap: () async {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => GroupProfileAddAdmin(
                              memberList: memberList
                                  .where(
                                      (element) => element?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_MEMBER)
                                  .toList(),
                              appbarTitle: TIM_t("设置管理员"),
                              selectCompletedHandler: (context, selectedMember) async {
                                if (selectedMember.isNotEmpty) {
                                  for (var member in selectedMember) {
                                    final isMute =
                                        (serverTime != null ? (member?.muteUntil ?? 0) > serverTime! : false);
                                    final userID = member!.userID;
                                    if (isMute) {
                                      widget.model.muteGroupMember(userID, false, serverTime);
                                    }
                                    widget.model.setMemberToAdmin(userID);
                                  }
                                }
                              },
                            ),
                          ),
                        );
                      },
                    ),
                    ...adminList
                        .map(
                          (e) => _buildListItem(
                            context,
                            e!,
                            ActionPane(
                              motion: const DrawerMotion(),
                              children: [
                                SlidableAction(
                                  onPressed: (_) {
                                    _removeAdmin(context, e);
                                  },
                                  flex: 1,
                                  backgroundColor: theme.cautionColor ?? CommonColor.cautionColor,
                                  autoClose: true,
                                  label: TIM_t("删除"),
                                )
                              ],
                            ),
                          ),
                        )
                        .toList(),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

/// 添加管理员
class GroupProfileAddAdmin extends StatefulWidget {
  final List<V2TimGroupMemberFullInfo?> memberList;
  final String appbarTitle;
  final void Function(BuildContext context, List<V2TimGroupMemberFullInfo?> selectedMemberList)? selectCompletedHandler;

  const GroupProfileAddAdmin({
    Key? key,
    required this.memberList,
    this.selectCompletedHandler,
    required this.appbarTitle,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _GroupProfileAddAdminState();
}

class _GroupProfileAddAdminState extends TIMUIKitState<GroupProfileAddAdmin> {
  List<V2TimGroupMemberFullInfo?> selectedMemberList = [];

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    final TUITheme theme = value.theme;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          widget.appbarTitle,
          style: const TextStyle(color: Colors.black, fontSize: 17),
        ),
        shadowColor: theme.weakDividerColor,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            color: Colors.white,
          ),
        ),
        iconTheme: const IconThemeData(
          color: Colors.white,
        ),
        leading: TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: Text(
            TIM_t("取消"),
            style: const TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
          ),
        ),
        actions: [
          if (selectedMemberList.isNotEmpty)
            TextButton(
              onPressed: () {
                if (widget.selectCompletedHandler != null) {
                  widget.selectCompletedHandler!(context, selectedMemberList);
                }
                if (selectedMemberList.isNotEmpty) {
                  CZMWidgetBuilderBridge.getInstance().showToast("设置成功");
                }
                Navigator.of(context).pop();
              },
              child: Text(
                TIM_t("完成"),
                style: const TextStyle(
                  color: Color(0xFF0E5AD3),
                  fontSize: 15,
                  fontWeight: FontWeight.w500,
                ),
              ),
            )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              alignment: Alignment.topLeft,
              color: theme.weakDividerColor,
              padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16),
              child: Text(
                TIM_t("群成员"),
                style: TextStyle(fontSize: 14, color: theme.weakTextColor),
              ),
            ),
            ...widget.memberList
                .map(
                  (e) => Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border(
                        bottom: BorderSide(color: theme.weakDividerColor ?? CommonColor.weakDividerColor),
                      ),
                    ),
                    padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                    child: InkWell(
                      onTap: () {
                        final isChecked = selectedMemberList.contains(e);
                        if (isChecked) {
                          selectedMemberList.remove(e);
                        } else {
                          selectedMemberList.add(e);
                        }
                        setState(() {});
                      },
                      child: Row(
                        children: [
                          CheckBoxButton(
                            onlyShow: true,
                            isChecked: selectedMemberList.contains(e),
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          SizedBox(
                            width: 36,
                            height: 36,
                            child: Avatar(
                              faceUrl: e?.faceUrl ?? "",
                              showName: _getShowName(e),
                              type: 2,
                            ),
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          Text(_getShowName(e), style: const TextStyle(fontSize: 16))
                        ],
                      ),
                    ),
                  ),
                )
                .toList(),
          ],
        ),
      ),
    );
  }
}
